﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Galaktika.BI.Runtime.Services;
using Galaktika.BI.Silverlight.ClientApp.Web.Runtime.Services;
using Galaktika.BI.Silverlight.ClientApp.Web.Runtime;
using Galaktika.BI.Silverlight.ClientApp.Web.Runtime.DataAccess;
using Ranet.AgOlap.Controls.PivotGrid.ClientServer;
using Ranet.Olap.Core.Data;

namespace Galaktika.BI.Silverlight.ClientApp.Web.Commands.PivotGrid
{
    public class GetPivotDataCommand : ServerCommand
    {
        public GetPivotDataCommand(InvokeSchema invoker)
            : base(Galaktika.BI.Silverlight.Commands.CommandId.GetPivotDataCommandId)
        {
            this.ContextId = invoker[KnownInvokeArgs.ContextId];
            this.DataSourceId = invoker[KnownInvokeArgs.DataSourceId];
            this.Args = invoker[KnownInvokeArgs.GetPivotDataCommand];
        }

        public string ContextId { get; private set; }
        public string DataSourceId { get; private set; }
        public string Args { get; private set; }

        private IBindingContext Context
        {
            get
            {
                return DataBinder.Current.GetContext(this.ContextId);
            }
        }

        private OlapDataManager DataManager
        {
            get
            {
                IBindingManager bindingMgr = DataBinder.Current.GetBindingManager(this.ContextId, this.DataSourceId);
                if (bindingMgr != null)
                {
                    return bindingMgr.DataManager as OlapDataManager;
                }

                return null;
            }
        }

        public override Galaktika.BI.Runtime.Services.InvokeResultSchema Invoke()
        {
            InvokeResultSchema res = new InvokeResultSchema(base.Id);
            res.ContentType = KnownContentTypes.MultidimData;

            PivotInitializeArgs args = XmlUtility.XmlStr2Obj<PivotInitializeArgs>(this.Args);
            if (DataManager != null && args != null)
            {
                // Заглушка - т.к. несколько раз была ситуация когда DataManager.Context оставался null
                if (DataManager.Context == null)
                    DataManager.Context = this.Context;
                
                CellSetData csd = DataManager.ExecuteQuery(args.Query);
                res.Content = XmlUtility.Obj2XmlStr(csd, Common.Namespace);
            }

            return res;
        }
    }
}
